package com.ds.esd.localproxy.handler.dsm;


import com.ds.common.JDSException;
import com.ds.context.JDSActionContext;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.editor.enums.PackagePathType;
import com.ds.esd.editor.enums.PackageType;
import com.ds.esd.localproxy.handler.AbstractRADHandler;
import com.ds.esd.tool.module.EUModule;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.web.RequestMethodBean;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;


public class DSMViewDispatcherHandler extends AbstractRADHandler {
    private String resourceMount;

    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        this.resourceMount = RESOURCE_MOUNT_OPTION.getProperty(server, handlerName);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }

    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        boolean ruleMatches = rule.matcher(request.getPath()).matches();
        if (!ruleMatches) {
            return false;
        }

        RequestMethodBean methodBean = this.getRequestMethodBean(request);
        if (methodBean == null) {
            return false;
        }
        String projectName = this.getProjectName(request);
        Map<String, Object> allParamsMap = this.getAllParamMap(methodBean, request);
        JDSActionContext.getActionContext().getContext().putAll(allParamsMap);
        try {
            ESDClient client = ESDFacrory.getESDClient();
            EUModule module = null;
            PackagePathType packagePathType = PackagePathType.startPath(methodBean.getUrl());
            if (packagePathType == null || packagePathType.getApiType().equals(PackageType.local)) {
                module = client.getCustomModule(methodBean.getUrl(), projectName, allParamsMap);
            } else {
                module = client.getDSMModule(methodBean.getUrl(), allParamsMap);
            }
            if (module != null) {
                JDSActionContext.getActionContext().getContext().put("projectName", projectName);
                JDSActionContext.getActionContext().getContext().put("className", module.getClassName());
                this.sendFtl(request, response, resourceMount + "/ftl/custom.ftl");
            } else {
                return false;
            }
        } catch (JDSException e) {
            response.sendError(500, e.getMessage());
            e.printStackTrace();
        }


        return true;
    }


}
